import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [{
	path: '/login',
	name: 'LoginRi',
	component: () => import("../views/LoginRi.vue")
}, {
	path: '*',
	name: 'error',
	component: () => import("../views/Error.vue")
},{
	path: '/Shop',
	name: 'shop',
	component: () => import("../views/Shop.vue")
},
]

const router = new VueRouter({
	routes
})

// 刷新页面会刷新路由
export const setRoutes = () => {
	const storeMenus = localStorage.getItem("menus");
	if (storeMenus) {
		// 拼装动态路由
		const manageRoute = {
			path: '/',
			name: '首页',
			component: () => import('../views/Manage.vue'),
			redirect: "/login",
			children: []
		}
		const menus = JSON.parse(storeMenus)
		menus.forEach(
			item => {
				console.log(item);
				if (item.path) { //当且仅当 path 不为空的时候才设置路由
					let itemMenu = {
						path: item.path,
						name: item.name,
						component: () => import('../views/' + item.pagePath + '.vue')
					}
					manageRoute.children.push(itemMenu)
				} else if (item.children.length) {
					item.children.forEach(item => {
						if (item.path) {
							let itemMenu = {
								path: item.path,
								name: item.name,
								component: () => import('../views/' + item.pagePath + '.vue')
							}
							manageRoute.children.push(itemMenu)
						}
					})
				}
			})

		// 获取当前路由对象名称数组
		const currentRoutes = router.getRoutes().map(v => v.name)
		if (!currentRoutes.includes('首页')) {
			// 动态添加到现在的路由对象中
			router.addRoute(manageRoute)
		}
	}
}

// 重置就 set 一次路由
setRoutes()

export default router
